<template>
  <div class="debounce-hook-demo p-4">
    <div class="space-y-6">
      <!-- 搜索输入防抖 -->
      <div class="debounce-section">
        <h4 class="debounce-title">搜索输入防抖 (300ms)</h4>
        <div class="space-y-3">
          <div class="search-container">
            <input v-model="searchInput" class="search-input" placeholder="输入搜索关键词..." />
            <div class="search-info">
              <div class="info-item">
                <span class="info-label">原始输入:</span>
                <span class="info-value">{{ searchInput }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">防抖后:</span>
                <span class="info-value">{{ debouncedSearch }}</span>
              </div>
            </div>
          </div>

          <div class="search-results">
            <div class="results-header">搜索结果:</div>
            <div v-if="!debouncedSearch" class="empty-results">请输入关键词进行搜索</div>
            <div v-else class="results-list">
              <div v-for="result in searchResults" :key="result" class="result-item">
                🔍 {{ result }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 按钮点击防抖 -->
      <div class="debounce-section">
        <h4 class="debounce-title">按钮点击防抖演示</h4>
        <div class="space-y-3">
          <div class="button-demo">
            <div class="demo-stats">
              <div class="stat-item">
                <div class="stat-label">实际点击次数</div>
                <div class="stat-value">{{ actualClicks }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">防抖后执行次数</div>
                <div class="stat-value">{{ debouncedClicks }}</div>
              </div>
            </div>

            <div class="button-controls">
              <button @click="handleClick" class="demo-button">快速点击我 (500ms 防抖)</button>
              <button @click="resetClicks" class="reset-button">重置计数</button>
            </div>

            <div class="click-log">
              <div class="log-header">点击日志:</div>
              <div class="log-content">
                <div v-for="(log, index) in clickLogs" :key="index" class="log-item">
                  {{ log }}
                </div>
                <div v-if="clickLogs.length === 0" class="empty-log">暂无点击记录</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- API 请求防抖 -->
      <div class="debounce-section">
        <h4 class="debounce-title">API 请求防抖模拟</h4>
        <div class="space-y-3">
          <div class="api-demo">
            <div class="request-form">
              <input
                v-model="apiQuery"
                class="api-input"
                placeholder="输入查询内容，模拟 API 请求..."
              />
              <div class="request-info">
                <div class="info-row">
                  <span>请求状态:</span>
                  <span :class="['status-badge', isRequesting ? 'status-loading' : 'status-idle']">
                    {{ isRequesting ? '请求中...' : '空闲' }}
                  </span>
                </div>
                <div class="info-row">
                  <span>实际请求次数:</span>
                  <span class="request-count">{{ requestCount }}</span>
                </div>
              </div>
            </div>

            <div class="api-results">
              <div class="results-header">模拟 API 响应:</div>
              <div v-if="apiResults.length === 0" class="empty-api-results">
                输入内容后将显示模拟的 API 响应
              </div>
              <div v-else class="api-response">
                <div v-for="(result, index) in apiResults" :key="index" class="response-item">
                  <div class="response-query">查询: "{{ result.query }}"</div>
                  <div class="response-data">结果: {{ result.data.length }} 条记录</div>
                  <div class="response-time">时间: {{ result.timestamp }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Hook 说明 -->
    <div class="mt-6 p-4 bg-yellow-50 border border-yellow-200 rounded">
      <h5 class="text-sm font-medium text-yellow-800 mb-2">⚡ useDebounce Hook 特性</h5>
      <ul class="text-xs text-yellow-700 space-y-1">
        <li>• <strong>性能优化</strong>: 减少高频操作的执行次数</li>
        <li>• <strong>用户体验</strong>: 避免过度的 API 请求和 UI 更新</li>
        <li>• <strong>灵活配置</strong>: 可自定义防抖延迟时间</li>
        <li>• <strong>多种场景</strong>: 适用于搜索、按钮点击、窗口调整等</li>
        <li>• <strong>取消机制</strong>: 支持手动取消和立即执行</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue'
import { useDebounceFn } from '@/hooks/useDebounce'

// 搜索输入防抖
const searchInput = ref('')
const debouncedSearch = ref('')

// 简单的防抖实现用于搜索
let searchTimeout: number | null = null

const clearSearchTimeout = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
    searchTimeout = null
  }
}

watch(searchInput, (newValue) => {
  clearSearchTimeout()

  searchTimeout = setTimeout(() => {
    debouncedSearch.value = newValue
    searchTimeout = null
  }, 300)
})

// 组件卸载时清理定时器
onUnmounted(() => {
  clearSearchTimeout()
})

// 模拟搜索结果
const searchResults = ref<string[]>([])
watch(debouncedSearch, (query) => {
  if (!query.trim()) {
    searchResults.value = []
    return
  }

  // 模拟搜索结果
  const mockResults = [
    `${query} - 相关文档`,
    `${query} - 教程指南`,
    `${query} - 最佳实践`,
    `${query} - 常见问题`,
    `${query} - API 参考`,
  ]
  searchResults.value = mockResults
})

// 按钮点击防抖
const actualClicks = ref(0)
const debouncedClicks = ref(0)
const clickLogs = ref<string[]>([])

const debouncedClickHandler = useDebounceFn(() => {
  debouncedClicks.value++
  const timestamp = new Date().toLocaleTimeString()
  clickLogs.value.unshift(`[${timestamp}] 防抖执行 - 第 ${debouncedClicks.value} 次`)

  // 限制日志数量
  if (clickLogs.value.length > 10) {
    clickLogs.value = clickLogs.value.slice(0, 10)
  }
}, 500)

const handleClick = () => {
  actualClicks.value++
  debouncedClickHandler.debouncedFn()
}

const resetClicks = () => {
  actualClicks.value = 0
  debouncedClicks.value = 0
  clickLogs.value = []
  debouncedClickHandler.cancel()
}

// API 请求防抖
const apiQuery = ref('')
const isRequesting = ref(false)
const requestCount = ref(0)
const apiResults = ref<
  Array<{
    query: string
    data: string[]
    timestamp: string
  }>
>([])

// 模拟 API 请求
const mockApiRequest = async (query: string) => {
  isRequesting.value = true
  requestCount.value++

  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 800))

  const mockData = [`${query} 相关数据 1`, `${query} 相关数据 2`, `${query} 相关数据 3`]

  apiResults.value.unshift({
    query,
    data: mockData,
    timestamp: new Date().toLocaleTimeString(),
  })

  // 限制结果数量
  if (apiResults.value.length > 5) {
    apiResults.value = apiResults.value.slice(0, 5)
  }

  isRequesting.value = false
}

const debouncedApiRequest = useDebounceFn((query: string) => {
  if (query.trim()) {
    mockApiRequest(query)
  }
}, 600)

watch(apiQuery, (newQuery) => {
  debouncedApiRequest.debouncedFn(newQuery)
})
</script>

<style scoped lang="scss">
.debounce-hook-demo {
  @apply bg-gray-50;
}

.debounce-section {
  @apply p-4 bg-white rounded-lg border border-gray-200;
}

.debounce-title {
  @apply text-base font-semibold text-gray-800 mb-4 pb-2 border-b border-gray-200;
}

.search-input,
.api-input {
  @apply w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent;
}

.search-info {
  @apply space-y-2 mt-3;
}

.info-item,
.info-row {
  @apply flex justify-between items-center text-sm;
}

.info-label {
  @apply font-medium text-gray-600;
}

.info-value {
  @apply font-mono bg-gray-100 px-2 py-1 rounded;
}

.search-results,
.api-results {
  @apply mt-4 p-3 bg-gray-100 rounded-lg;
}

.results-header {
  @apply text-sm font-medium text-gray-700 mb-2;
}

.empty-results,
.empty-api-results {
  @apply text-sm text-gray-500 text-center py-2;
}

.results-list {
  @apply space-y-1;
}

.result-item {
  @apply text-sm text-gray-700 p-2 bg-white rounded border;
}

.demo-stats {
  @apply grid grid-cols-2 gap-4 mb-4;
}

.stat-item {
  @apply text-center p-3 bg-gray-100 rounded-lg;
}

.stat-label {
  @apply text-sm text-gray-600 mb-1;
}

.stat-value {
  @apply text-2xl font-bold text-blue-600;
}

.button-controls {
  @apply flex justify-center space-x-3 mb-4;
}

.demo-button {
  @apply px-6 py-3 bg-blue-500 text-white rounded-lg font-medium hover:bg-blue-600 transition-colors;
}

.reset-button {
  @apply px-4 py-3 bg-gray-500 text-white rounded-lg font-medium hover:bg-gray-600 transition-colors;
}

.click-log {
  @apply mt-4;
}

.log-header {
  @apply text-sm font-medium text-gray-700 mb-2;
}

.log-content {
  @apply bg-gray-900 rounded-lg p-3 max-h-40 overflow-y-auto;
}

.log-item {
  @apply text-sm text-green-400 font-mono mb-1;
}

.empty-log {
  @apply text-sm text-gray-400;
}

.request-form {
  @apply space-y-3;
}

.request-info {
  @apply space-y-2;
}

.status-badge {
  @apply px-2 py-1 rounded text-xs font-medium;

  &.status-idle {
    @apply bg-green-100 text-green-700;
  }

  &.status-loading {
    @apply bg-yellow-100 text-yellow-700;
  }
}

.request-count {
  @apply font-bold text-blue-600;
}

.api-response {
  @apply space-y-3;
}

.response-item {
  @apply p-3 bg-white rounded-lg border border-gray-200;
}

.response-query {
  @apply font-medium text-gray-800 mb-1;
}

.response-data {
  @apply text-sm text-blue-600 mb-1;
}

.response-time {
  @apply text-xs text-gray-500;
}
</style>
